package com.kuiandjie.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kuiandjie.entity.Document;
import com.kuiandjie.util.DBHelp;
import com.kuiandjie.util.RowMapper;

public class DocumentDao {
	private DBHelp<Document> db = new DBHelp<Document>();
	
	private class DocumentRowMapper implements RowMapper<Document>{

		@Override
		public Document mapperRow(ResultSet rs) throws SQLException {
			Document d = new Document();
				d.setCreateTime(rs.getString("createtime"));
				d.setContent(rs.getString("content"));
				d.setEmpId(rs.getInt("employeeid"));
				d.setId(rs.getInt("id"));
				d.setProId(rs.getInt("projectid"))	;
				d.setTitle(rs.getString("title"));
				d.setEmpName(rs.getString("empname"));
				return d;
		}
		
	}

	public List<Document> findAllDocumentByProId(int curpid) {
		String sql = "SELECT t_document.id,title,content,createtime ,employeeid,projectid,t_employee.name as empname FROM t_document LEFT JOIN t_employee ON t_document.employeeid = t_employee.id WHERE t_document.projectid = ? ORDER BY createtime DESC";
		return db.executeQueryForList(sql, new DocumentRowMapper(), curpid);
	}

	public int saveDocument(Document d) {
		String sql = "INSERT INTO t_document(title,content,createtime,employeeid,projectid) values(?,?,?,?,?)";
		return db.getAutoKey(sql, d.getTitle(),d.getContent(),d.getCreateTime(),d.getEmpId(),d.getProId());
	}

	public Document findDocumentById(String did) {
		String sql = "SELECT id,title,title as empname,content,createtime,employeeid,projectid FROM t_document WHERE id = ?";
		
		return db.executeQueryForObject(sql, new DocumentRowMapper(), did);
	}

	public void editDocument(String title, String content,String did) {
		String sql = "UPDATE t_document SET title = ?, content=? WHERE id =?";
		db.executeSQL(sql, title,content,Integer.parseInt(did));
		
	}

	public void deleteDocument(String did) {
		String sql = "DELETE FROM t_document WHERE id = ?";
		db.executeSQL(sql, Integer.parseInt(did));
				
		
	}

	public Document findDocumentByIdAndDid(int id, String did) {
		String sql = "SELECT id,title,title as empname,content,createtime,employeeid,projectid FROM t_document WHERE employeeid = ? AND id= ?";
		return db.executeQueryForObject(sql, new DocumentRowMapper(), id,did);
	}

}
